package com.example.dao;

import com.example.domain.User;
import com.example.util.DBUtil;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.security.MessageDigest;
import java.nio.charset.StandardCharsets;

public class UserDao {

    /**
     * Create - 创建用户
     */
    public void createUser(User user) throws SQLException {
        if (user == null || user.getUsername() == null || user.getEmail() == null || user.getPassword() == null) {
            throw new IllegalArgumentException("用户信息不完整");
        }
        
        // 加密密码
        String encryptedPassword = encryptPassword(user.getPassword());
        
        String sql = "INSERT INTO tb_user (username, realname, password, email, phone, address) VALUES (?, ?, ?, ?, ?, ?)";
        Connection conn = null;
        PreparedStatement stmt = null;
        
        try {
            conn = DBUtil.getConnection();
            stmt = conn.prepareStatement(sql);
            stmt.setString(1, user.getUsername());
            stmt.setString(2, user.getRealname());
            stmt.setString(3, encryptedPassword);
            stmt.setString(4, user.getEmail());
            stmt.setString(5, user.getPhone());
            stmt.setString(6, user.getAddress() != null ? user.getAddress() : "");
            stmt.executeUpdate();
        } finally {
            DBUtil.closeStatement(stmt);
            DBUtil.closeConnection(conn);
        }
    }

    /**
     * Read - 根据ID查询用户
     */
    public Optional<User> getUserById(int id) throws SQLException {
        if (id <= 0) {
            return Optional.empty();
        }
        
        String sql = "SELECT * FROM tb_user WHERE id = ?";
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        
        try {
            conn = DBUtil.getConnection();
            stmt = conn.prepareStatement(sql);
            stmt.setInt(1, id);
            rs = stmt.executeQuery();
            
            if (rs.next()) {
                User user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setRealname(rs.getString("realname"));
                user.setPassword(rs.getString("password"));
                user.setEmail(rs.getString("email"));
                user.setPhone(rs.getString("phone"));
                user.setAddress(rs.getString("address"));
                return Optional.of(user);
            }
        } finally {
            DBUtil.closeAll(rs, stmt, conn);
        }
        return Optional.empty();
    }

    /**
     * Read - 查询所有用户
     */
    public List<User> getAllUsers() throws SQLException {
        List<User> users = new ArrayList<>();
        String sql = "SELECT * FROM tb_user";
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        
        try {
            conn = DBUtil.getConnection();
            stmt = conn.prepareStatement(sql);
            rs = stmt.executeQuery();
            
            while (rs.next()) {
                User user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setRealname(rs.getString("realname"));
                user.setPassword(rs.getString("password"));
                user.setEmail(rs.getString("email"));
                user.setPhone(rs.getString("phone"));
                user.setAddress(rs.getString("address"));
                users.add(user);
            }
        } finally {
            DBUtil.closeAll(rs, stmt, conn);
        }
        return users;
    }

    /**
     * Update - 更新用户
     */
    public void updateUser(User user) throws SQLException {
        if (user == null || user.getId() <= 0 || user.getUsername() == null || user.getEmail() == null) {
            throw new IllegalArgumentException("用户信息不完整或无效");
        }
        
        String sql = "UPDATE tb_user SET username = ?, realname = ?, email = ?, phone = ?, address = ?";
        if (user.getPassword() != null) {
            sql += ", password = ?";
        }
        sql += " WHERE id = ?";
        
        Connection conn = null;
        PreparedStatement stmt = null;
        
        try {
            conn = DBUtil.getConnection();
            stmt = conn.prepareStatement(sql);
            int paramIndex = 1;
            stmt.setString(paramIndex++, user.getUsername());
            stmt.setString(paramIndex++, user.getRealname());
            stmt.setString(paramIndex++, user.getEmail());
            stmt.setString(paramIndex++, user.getPhone());
            stmt.setString(paramIndex++, user.getAddress() != null ? user.getAddress() : "");
            
            if (user.getPassword() != null) {
                // 加密密码
                stmt.setString(paramIndex++, encryptPassword(user.getPassword()));
            }
            
            stmt.setInt(paramIndex++, user.getId());
            stmt.executeUpdate();
        } finally {
            DBUtil.closeStatement(stmt);
            DBUtil.closeConnection(conn);
        }
    }

    /**
     * Delete - 删除用户
     */
    public void deleteUser(int id) throws SQLException {
        if (id <= 0) {
            throw new IllegalArgumentException("无效的用户ID");
        }
        
        String sql = "DELETE FROM tb_user WHERE id = ?";
        Connection conn = null;
        PreparedStatement stmt = null;
        
        try {
            conn = DBUtil.getConnection();
            stmt = conn.prepareStatement(sql);
            stmt.setInt(1, id);
            stmt.executeUpdate();
        } finally {
            DBUtil.closeStatement(stmt);
            DBUtil.closeConnection(conn);
        }
    }

    /**
     * 根据用户名和密码验证用户
     */
    public User authenticate(String username, String password) throws SQLException {
        if (username == null || password == null) {
            return null;
        }
        
        // 加密密码
        String encryptedPassword = encryptPassword(password);
        
        String sql = "SELECT * FROM tb_user WHERE username = ? AND password = ?";
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        
        try {
            conn = DBUtil.getConnection();
            stmt = conn.prepareStatement(sql);
            stmt.setString(1, username);
            stmt.setString(2, encryptedPassword);
            rs = stmt.executeQuery();
            
            if (rs.next()) {
                User user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setRealname(rs.getString("realname"));
                user.setEmail(rs.getString("email"));
                user.setPhone(rs.getString("phone"));
                user.setAddress(rs.getString("address"));
                // 不返回密码
                user.setPassword(null);
                return user;
            }
        } finally {
            DBUtil.closeAll(rs, stmt, conn);
        }
        return null;
    }

    /**
     * 根据用户名检查用户是否存在
     */
    public boolean userExists(String username) throws SQLException {
        if (username == null) {
            return false;
        }
        
        String sql = "SELECT COUNT(*) FROM tb_user WHERE username = ?";
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        
        try {
            conn = DBUtil.getConnection();
            stmt = conn.prepareStatement(sql);
            stmt.setString(1, username);
            rs = stmt.executeQuery();
            
            if (rs.next()) {
                return rs.getInt(1) > 0;
            }
        } finally {
            DBUtil.closeAll(rs, stmt, conn);
        }
        return false;
    }

    /**
     * 根据用户名查询用户
     */
    public User getUserByUsername(String username) throws SQLException {
        if (username == null) {
            return null;
        }
        
        String sql = "SELECT * FROM tb_user WHERE username = ?";
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        
        try {
            conn = DBUtil.getConnection();
            stmt = conn.prepareStatement(sql);
            stmt.setString(1, username);
            rs = stmt.executeQuery();
            
            if (rs.next()) {
                User user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setRealname(rs.getString("realname"));
                user.setPassword(rs.getString("password"));
                user.setEmail(rs.getString("email"));
                user.setPhone(rs.getString("phone"));
                user.setAddress(rs.getString("address"));
                return user;
            }
        } finally {
            DBUtil.closeAll(rs, stmt, conn);
        }
        return null;
    }
    
    /**
     * 使用SHA-256加密密码
     */
    private String encryptPassword(String password) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            byte[] hash = md.digest(password.getBytes(StandardCharsets.UTF_8));
            StringBuilder hexString = new StringBuilder();
            for (byte b : hash) {
                hexString.append(String.format("%02x", b));
            }
            return hexString.toString();
        } catch (Exception e) {
            // 如果加密失败，记录错误并返回原始密码（这不是理想情况，但至少做了尝试）
            System.err.println("密码加密失败: " + e.getMessage());
            return password;
        }
    }
}